import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getWithAuth } from "@/utils/request";

// 定义接口响应数据类型
interface PickingGroup {
  address: {
    receiverName: string;
    receiverPhone: string;
    receiverProvince: string;
    receiverCity: string;
    receiverDistrict: string;
    receiverAddress: string;
    postcode?: string;
  };
  orders: Array<{
    orderInfo: {
      orderNo: string;
      remark?: string;
    };
    items: Array<{
      spuName: string;
      skuSpecs: string;
      skuNumber: number;
      unitPrice: number;
      totalPrice: number;
      actualPrice: number;
    }>;
  }>;
  orderNos: string[];
  totalQuantity: number;
  totalAmount: number;
}

interface SkuItem {
  spuName: string;
  skuSpecs: string;
  totalQuantity: number;
  totalActualPrice: number;
  unitPrice: number;
  orders: string[];
}

export function useOutboundCsvExport() {
  const exportLoading = ref(false);

  // 导出配货单
  const handleExportPicking = async () => {
    exportLoading.value = true;
    try {
      const response = await getWithAuth("/internal/order/outboundOrder");

      if (response.code === 0 && response.data) {
        const date = new Date().toISOString().split("T")[0];
        const filename = `配货单_${date}.csv`;
        exportToCSV(response.data, filename);
        ElMessage.success("导出成功");
      } else {
        ElMessage.error(response.message || "获取配货数据失败");
      }
    } catch (error) {
      console.error("导出配货单失败:", error);
      ElMessage.error("导出配货单失败");
    } finally {
      exportLoading.value = false;
    }
  };

  // CSV导出功能
  const exportToCSV = (data: PickingGroup[], filename: string) => {
    if (!data || data.length === 0) {
      ElMessage.warning("没有数据可导出");
      return;
    }

    try {
      const csvContent = buildCsvContent(data);
      const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
      const link = document.createElement("a");

      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", filename);
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      }
    } catch (error) {
      console.error("导出失败:", error);
      ElMessage.error("导出失败");
    }
  };

  // 构建CSV内容
  const buildCsvContent = (pickingGroups: PickingGroup[]): string => {
    const csvLines: string[] = [];

    csvLines.push("\uFEFF");
    csvLines.push(
      "收货人,电话,省份,城市,区县,详细地址,邮编,商品名称,规格,数量,单价,实际金额,备注"
    );

    pickingGroups.forEach((group, groupIndex) => {
      const address = group.address;
      const mergedItems = mergeSkuItems(group);

      mergedItems.forEach((item, itemIndex) => {
        const csvLine: any[] = [];

        if (itemIndex === 0) {
          csvLine.push(
            escapeCsvField(address.receiverName),
            escapeCsvField(address.receiverPhone),
            escapeCsvField(address.receiverProvince),
            escapeCsvField(address.receiverCity),
            escapeCsvField(address.receiverDistrict),
            escapeCsvField(address.receiverAddress),
            escapeCsvField(address.postcode || "")
          );
        } else {
          csvLine.push("", "", "", "", "", "", "");
        }

        csvLine.push(
          escapeCsvField(item.spuName),
          escapeCsvField(formatSpecs(item.skuSpecs)),
          item.totalQuantity,
          item.unitPrice,
          item.totalActualPrice,
          escapeCsvField(getGroupRemark(group))
        );

        csvLines.push(csvLine.join(","));
      });

      csvLines.push(
        [
          "汇总",
          "",
          "",
          "",
          "",
          "",
          "",
          `商品种类: ${mergedItems.length}`,
          `商品总数: ${group.totalQuantity}`,
          "",
          "",
          group.totalAmount,
          `订单数: ${group.orderNos.length}`,
          `订单号: ${group.orderNos.join("、")}`,
        ].join(",")
      );

      if (groupIndex < pickingGroups.length - 1) {
        csvLines.push("");
      }
    });

    return csvLines.join("\n");
  };

  // 合并相同规格的商品
  const mergeSkuItems = (group: PickingGroup): SkuItem[] => {
    const skuMap = new Map<string, SkuItem>();

    group.orders.forEach((order) => {
      order.items.forEach((item) => {
        const skuKey = `${item.spuName}-${item.skuSpecs}`;

        if (skuMap.has(skuKey)) {
          const existingItem = skuMap.get(skuKey)!;
          existingItem.totalQuantity += item.skuNumber;
          existingItem.totalActualPrice += item.actualPrice;
          if (!existingItem.orders.includes(order.orderInfo.orderNo)) {
            existingItem.orders.push(order.orderInfo.orderNo);
          }
        } else {
          skuMap.set(skuKey, {
            spuName: item.spuName,
            skuSpecs: item.skuSpecs,
            totalQuantity: item.skuNumber,
            totalActualPrice: item.actualPrice,
            unitPrice: item.unitPrice,
            orders: [order.orderInfo.orderNo],
          });
        }
      });
    });

    return Array.from(skuMap.values());
  };

  // 获取组的备注信息
  const getGroupRemark = (group: PickingGroup): string => {
    for (const order of group.orders) {
      if (order.orderInfo.remark) {
        return order.orderInfo.remark;
      }
    }
    return "";
  };

  // CSV字段转义处理
  const escapeCsvField = (field: any): string => {
    if (field === null || field === undefined) {
      return "";
    }

    const stringField = String(field);
    if (
      stringField.includes(",") ||
      stringField.includes("\n") ||
      stringField.includes('"')
    ) {
      return `"${stringField.replace(/"/g, '""')}"`;
    }

    return stringField;
  };

  // 格式化规格信息
  const formatSpecs = (skuSpecs: string): string => {
    try {
      const specs = JSON.parse(skuSpecs);
      return Object.entries(specs)
        .map(([key, value]) => `${key}:${value}`)
        .join("; ");
    } catch (e) {
      return skuSpecs;
    }
  };

  return {
    exportLoading,
    handleExportPicking,
  };
}
